<?php

namespace app\user\controller;

use app\common\controller\CommonController;
use think\Exception;
use app\common\entity\RequestEntity;
use think\Db;
use app\common\extend\Tools;
use app\common\base\_Db;
use think\Loader;

class Staff extends CommonController{
    /**
     * 添加员工
     */
    public function AddStaff(){
        $Account = new RequestEntity('Account', '账号', false, 32);
        $Phone = new RequestEntity('Phone','电话号码',false,32);
        //账号校验
        $res_account = _Db::GetData('staff',array('staff_id'=>'uid'),'account = "'.$Account->text.'"');
        //手机号校验
        $res_phone = _Db::GetData('staff',array('staff_id'=>'uid'),'phone_number = '.$Phone->text);
        if (!empty($res_account)){
            _Db::Response(2,'账号已存在');
        }elseif (!empty($res_phone)){
            _Db::Response(2,'手机号已存在');
        }
        else{
            $Password = new RequestEntity('Password', '密码', false, 32);
            $Name = new RequestEntity('Name', 'Name', false, 32);
            $Number = new RequestEntity('Number', '工号', false, 32);
            $Status = new RequestEntity('Status','是否有效',false,32);
            $Sex = new RequestEntity('Sex','性别',false,32);
            $DepartmentId = new RequestEntity('DepartmentId','部门Id',false,32);
            //$CardBus = new RequestEntity('CardBus','班车卡号',false,32);
            $CardRest = new RequestEntity('CardRest','饭卡卡号',false,32);
            /*$PositionId = new RequestEntity('PositionId','职位Id',false,32);
            $ManagerId = new RequestEntity('ManagerId','上级领导Id',false,32);*/
            $RoleId = new RequestEntity('RoleId','RoleId',false,32);
            $CreatId =  new RequestEntity('CreatId','CreatId',false,32);
            $ro =file_get_contents('php://input'); //获取json文件
            $reg=json_decode($ro,true); //将json转为PHP数组，供操作
            $PicUrl = Tools::uploads($reg['Img'],'staff');
            $field = array(
                'account'=>$Account->text,
                'nick_name'=>$Name->text,
                'login_time'=>date('Y-m-d H:i:s',time()),
                'status'=>$Status->text,
                'gender'=>$Sex->text,
                'phone_number'=>$Phone->text,
                'department_id'=>$DepartmentId->text
            );
            //密码
            if (!empty($Password->text)){
                $field['password'] = md5($Password->text);
            }else{
                $field['password'] = md5(123456);
            }
            //饭卡卡号
            if (!empty($CardRest->text)){
                $field['card_rest'] = $CardRest->text;
            }else{
                $field['card_rest'] = 123456;
            }
            //工号
            if (!empty($Number->text)){
                $field['number'] = $Number->text;
            }else{
                $field['number'] = 123456;
            }
            //照片
            if (!empty($PicUrl)){
                $field['pic_url'] = $PicUrl;
            }
            if($id = Db::name('staff')->insertGetId($field))
            {
                Db::name('staff_role')
                    ->insert([
                        'staff_id'=>$id,
                        'role_id'=>$RoleId->text,
                        'oper_id'=>$CreatId->text,
                        'oper_date'=>date('Y-m-d H:i:s',time())
                    ]);
                _Db::log($CreatId->text,1,'员工添加');
                $this->ListStaff();
            }else{
                _Db::Response(0,'添加失败');
            }
        }
    }
    public function RoleList(){
        $res = Db::name('role')
            ->field('role_id,role_name')
            ->select();
        return json_encode($res);
    }
    /**
     * 员工列表
     */
    public function ListStaff(){
        $param_page = $get_page = input('Page', 1);
        $param_pagesize =  10;
        $get_name = new RequestEntity('name', '姓名', false, 0);
        $post_depart = new RequestEntity('depart', '部门', false, 0);
        $post_role = new RequestEntity('role', '角色', false, 0);
        $post_regist = new RequestEntity('regist', '认证状态', false, 0);
        $where = 1;
        if (!empty($get_name->text)){
            $where .= ' and s.nick_name  like "%' . $get_name->text.'%"';
        }
        if (!empty($post_depart->text)){
            $where .= ' and s.department_id = ' . $post_depart->text;
        }
        if (!empty($post_role->text)){
            $where .= ' and rr.role_id  =' . $post_role->text;
        }
        if (!empty($post_regist->text)){
            $where .=' and s.regist = ' . $post_regist->text;
        }
        $res = Db::name('staff')->alias('s')
            ->field(
                's.staff_id as Id,
                s.nick_name as Name,
                s.number as Number,
                s.status as Status,
                s.gender as Sex,
                s.phone_number as Phone,
                s.department_id as DepartmentId,
                s.oper_id as Operator,
                s.regist as Regist,
                s.pic_url as Url,
                r.staff_id as StaffId,
                rr.role_id as RoleId,rr.role_name as RoleName,d.depart_name'
            )
            ->join('staff_role r','s.staff_id = r.staff_id','LEFT')
            ->join('role rr','r.role_id = rr.role_id','LEFT')
            ->join('department d','s.department_id = d.depart_id','LEFT')
            ->where($where)
            ->limit(($param_page - 1) * $param_pagesize, $param_pagesize)
            ->select();
        foreach ( $res as $key => $value){
            $res[$key]['Url'] = HttpPath .$value ['Url'];
            if ($value['Regist'] == 1){
                $res[$key]['registName'] = '未绑定';
            }elseif ($value['Regist'] == 2){
                $res[$key]['registName'] = '已绑定';
            }
//            elseif ($value['Regist'] == 3){
//                $res[$key]['registName'] = '已审核';
//            }elseif ($value['Regist'] == 4){
//                $res[$key]['registName'] = '已驳回';
//            }
            if($res[$key]['Operator']){//操作者id 转换姓名
                $res[$key]['Operator']=$this->GetUserName($value['Operator']);
            }
            if($res[$key]['DepartmentId']){
                $res[$key]['DepartmentId'] = $this->GetDepartName($value['DepartmentId']);
            }
            $res[$key]['Order'] = $key + 1;
        }
        $int_total_count = count(Db::name('staff')->alias('s')
            ->join('staff_role r','s.staff_id = r.staff_id','LEFT')
            ->join('role rr','r.role_id = rr.role_id','LEFT')
            ->join('department d','s.department_id = d.depart_id','LEFT')
            ->where($where)
            ->select());
        $data['tableData']=$res;
        $data['TotalCount'] = $int_total_count;
        $data['Page'] = (int)$param_page;
        $data['PageSize'] = (int)$param_pagesize;
        //return ResponseJson::Json($data);
        _Db::ResponseJson($data);
    }
    public function GetDepartName($id){
        $res = Db::name('department')
            ->field('depart_name')
            ->where('depart_id ='.$id)
            ->find();
        return $res['depart_name'];
    }
    public function GetUserName($id){
        $res = Db::name('staff')
            ->field('nick_name')
            ->where('staff_id ='.$id)
            ->find();
        return $res['nick_name'];
    }
    /**
     * 员工详情
     */
    public function ItemStaff(){
        $StaffId = new RequestEntity('StaffId', '序号', false, 32);
        $res = Db::name('staff')->alias('s')
            ->field(
                [
                    's.staff_id as Id',
                    's.account as Account',
                    's.password as Password',
                    's.nick_name as Name',
                    's.number as Number',
                    's.login_time as Logintime',
                    's.status as Status',
                    's.gender as Sex',
                    's.phone_number as Phone',
                    's.card_bus as Card',
                    's.card_rest as Cardrest',
                    's.posit_id as Positid',
                    's.manager_id as Managerid',
                    's.pic_url as Url',
                    's.regist as Regist',
                    'l.role_id as RoleId',
                    'l.role_name as RoleName',
                    'd.depart_id as DepartId',
                    'd.depart_name as DepartName'
                ]
            )
            ->join('staff_role f','f.staff_id = s.staff_id','LEFT')
            ->join('role l','l.role_id = f.role_id','LEFT')
            ->join('department d','s.department_id = d.depart_id','LEFT')
            ->where('s.staff_id ='.$StaffId->text)
            ->find();
        $res['Url'] = HttpPath.$res['Url'];
            //echo Db::table('')->getLastSql();
        //return ResponseJson::Json($res);
        _Db::ResponseJson($res);
    }
    /**
     * 角色列表
     */
    public function GetRoleList(){
        $fields = [
            'role_id'=>'Rid',
            'role_name'=>'RoleName'
        ];
       $res = _Db::GetDataList('role',$fields,'');
       return json_encode($res);
    }
    /**
     * 部门列表   
     */
    public function GetDepartList(){
        $fields = [
            'depart_id'=>'Did',
            'depart_name'=>'DepartName'
        ];
        $res = _Db::GetDataList('department',$fields,'');
        return json_encode($res);
    }
    /**
     * 员工修改
     */
    public function ModifyStaff(){
        $StaffId = new RequestEntity('StaffId','ID',false,32);
        $Phone = new RequestEntity('Phone','电话号码',false,32);
        $Number = new RequestEntity('Number', '工号', false, 32);
        $CardRest = new RequestEntity('CardRest','饭卡卡号',false,32);
        $Account = new RequestEntity('Account', '账号', false, 32);
        //$Password = new RequestEntity('Password', '密码', false, 32);
        $Status = new RequestEntity('Status','是否有效',false,32);
        $Sex = new RequestEntity('Sex','性别',false,32);
        $DepartmentId = new RequestEntity('DepartmentId','部门Id',false,32);
        //$CardBus = new RequestEntity('CardBus','公交卡号',false,32);
        $RoleId = new RequestEntity('RoleId','角色Id',false,32);
        $Name = new RequestEntity('Name','姓名',false,32);
        $CreatId = new RequestEntity('CreatId','操作人',false,32);
        $ro =file_get_contents('php://input'); //获取json文件
        $reg=json_decode($ro,true); //将json转为PHP数组，供操作
        $field = array(
            'account'=>$Account->text,
            /*'password'=>$Password->text,*/
            'nick_name'=>$Name->text,
            'status'=>$Status->text,
            'gender'=>$Sex->text,
            'phone_number'=>$Phone->text,
            'department_id'=>$DepartmentId->text,
            //'card_bus'=>$CardBus->text,
            'oper_date'=>date('Y-m-d H:i:s',time()),
            'oper_id'=>$CreatId->text
        );
        //饭卡卡号
        if (!empty($CardRest->text)){
            $field['card_rest'] = $CardRest->text;
        }
        //工号
        if (!empty($Number->text)){
            $field['number'] = $Number->text;
        }
        //图片
        if (!empty($reg['Img'])){
            $PicUrl = Tools::uploads($reg['Img'],'staff');
            $field['pic_url'] = $PicUrl;
        }
        //手机号校验
        $res_phone = _Db::GetData('staff',array('staff_id'=>'uid'),'staff_id !='.$StaffId->text.' and phone_number = '.$Phone->text);
        if (!empty($res_phone)){
            _Db::Response(2,'手机号已存在');
        }else{
            try{
                Db::name('staff')->where('staff_id ='.$StaffId->text)->update($field);
                $info = Db::table('staff_role')->where('staff_id ='.$StaffId->text)->find();
                if (empty($info)){
                    $insert = array(
                        'role_id'=>$RoleId->text,
                        'staff_id'=>$StaffId->text,
                        'oper_date'=>date('Y-m-d H:i:s',time()),
                        'oper_id'=>$CreatId->text
                    );
                    Db::name('staff_role')->insert($insert);
                }elseif(($RoleId->text!=$info['role_id'])){
                    Db::name('staff_role')->where('staff_id ='.$StaffId->text)->update(['role_id'=>$RoleId->text]);
                }
                _Db::log($CreatId->text,3,'员工修改');
                $this->Item($StaffId->text);
            }catch (Exception $exception){
                _Db::Response(0,'修改失败');
            }
        }
    }
    /**
     * 员工删除
     */
    public function RemoveStaff(){
        $StaffId = new RequestEntity('StaffId', 'ID', false, 32);
        $CreatId = new RequestEntity('CreatId', 'CreatId', false, 32);
        if($StaffId->text == 1){
            _Db::Response(3,'管理员不能删除');
        }
        $res = _Db::GetData('staff','openid,regist','staff_id = '.$StaffId->text);
        if(
            Db::name('staff')
            ->where('staff_id ='.$StaffId->text)
            ->delete()
        ){
            //员工已审核，删除该员工时删除用户表对应数据
            if ($res['openid']!=''&&$res['regist']==3){
                Db::name('user')->where('openid ='.$res['openid'])->delete();
            }
            //删除关联表
            Db::name('staff_role')->where('staff_id ='.$StaffId->text)->delete();
            _Db::log($CreatId->text,2,'员工删除');
            $this->ListStaff();
        }else{
            _Db::Response(0,'删除失败');
        }
    }
    //审核
    public function SwitchModity(){
        //获取请求参数
        $request_data = [
            $post_itemid = new RequestEntity('StaffId', 'ID', true, 10),
            $post_value = new RequestEntity('Value', '值', true, 10),
            $post_creatid = new RequestEntity('CreatId','操作人Id', false, 30),
        ];
        //设置条件
        $param_where = [
            'staff_id' => $post_itemid->text,
        ];
        $res = _Db::GetData('staff','openid',$param_where);
        //表单内容验证
        _Db::Validates($request_data);
        if ($post_value->text == 3){
            $type = 7;
            $content = '人员审核';
            $param_field = [
                'regist'    => 3,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
            if (!empty($res)){
                Db::name('user')->where('openid ="'.$res['openid'].'"')->update(['iden'=>2]);
            }
        }elseif ($post_value->text == 4){
            $type = 8;
            $content = '审核驳回';
            $param_field = [
                'regist'    => 4,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
            if (!empty($res)){
                Db::name('user')->where('openid ="'.$res['openid'].'"')->update(['iden'=>1]);
            }
        }
        $result = Db::table('staff')
            ->where($param_where)
            ->update($param_field);
        if ($result){
            _Db::log($post_creatid->text,$type,$content);
            $this->Item($post_itemid->text);
        }
    }
    public function Item($id){
        $res = Db::name('staff')->alias('s')
            ->field(
                [
                    's.staff_id as Id',
                    's.account as Account',
                    's.password as Password',
                    's.nick_name as Name',
                    's.number as Number',
                    's.login_time as Logintime',
                    's.status as Status',
                    's.gender as Sex',
                    's.phone_number as Phone',
                    's.card_bus as Card',
                    's.card_rest as Cardrest',
                    's.posit_id as Positid',
                    's.manager_id as Managerid',
                    's.pic_url as Url',
                    's.regist as Regist',
                    'l.role_id as RoleId',
                    'l.role_name as RoleName',
                    'd.depart_id as DepartId',
                    'd.depart_name as DepartName'
                ]
            )
            ->join('staff_role f','f.staff_id = s.staff_id','LEFT')
            ->join('role l','l.role_id = f.role_id','LEFT')
            ->join('department d','s.department_id = d.depart_id','LEFT')
            ->where('s.staff_id ='.$id)
            ->find();
        $res['Url'] = HttpPath.$res['Url'];
        _Db::ResponseJson($res);
    }
    public function Staffexcel(){
        //查询
        $param_page = $get_page = input('Page', 1);
        $param_pagesize =  10;
        $get_name = new RequestEntity('name', '姓名', false, 0);
        $post_depart = new RequestEntity('depart', '部门', false, 0);
        $post_role = new RequestEntity('role', '角色', false, 0);
        $post_regist = new RequestEntity('regist', '认证状态', false, 0);
        $where = 1;
        if (!empty($get_name->text)){
            $where .= ' and s.nick_name  like "%' . $get_name->text.'%"';
        }
        if (!empty($post_depart->text)){
            $where .= ' and s.department_id = ' . $post_depart->text;
        }
        if (!empty($post_role->text)){
            $where .= ' and rr.role_id  =' . $post_role->text;
        }
        if (!empty($post_regist->text)){
            $where .=' and s.regist = ' . $post_regist->text;
        }
        $res = Db::name('staff')->alias('s')
            ->field(
                's.staff_id as Id,
                s.nick_name as Name,
                s.number as Number,
                s.status as Status,
                s.gender as Sex,
                s.phone_number as Phone,
                s.department_id as DepartmentId,
                s.oper_id as Operator,
                s.regist as Regist,
                s.pic_url as Url,
                r.staff_id as StaffId,
                rr.role_id as RoleId,rr.role_name as RoleName,d.depart_name'
            )
            ->join('staff_role r','s.staff_id = r.staff_id','LEFT')
            ->join('role rr','r.role_id = rr.role_id','LEFT')
            ->join('department d','s.department_id = d.depart_id','LEFT')
            ->where($where)
            ->select();
        foreach ( $res as $key => $value){
            if ($value['Regist'] == 1){
                $res[$key]['Regist'] = '未绑定';
            }elseif ($value['Regist'] == 2){
                $res[$key]['Regist'] = '已绑定';
            }
//            elseif ($value['Regist'] == 3){
//                $res[$key]['registName'] = '已审核';
//            }elseif ($value['Regist'] == 4){
//                $res[$key]['registName'] = '已驳回';
//            }
            if($res[$key]['Operator']){//操作者id 转换姓名
                $res[$key]['Operator']=$this->GetUserName($value['Operator']);
            }
            if($res[$key]['DepartmentId']){
                $res[$key]['DepartmentId'] = $this->GetDepartName($value['DepartmentId']);
            }
            $res[$key]['Order'] = $key + 1;
        }

        $PHPExcel = new \PHPExcel();
//         print_r($PHPExcel);die;
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle("订单信息");
        $PHPSheet->setCellValue("A1","姓名");
        $PHPSheet->setCellValue("B1","工号");
        $PHPSheet->setCellValue("C1","所在部门");
        $PHPSheet->setCellValue("D1","角色");
        $PHPSheet->setCellValue("E1","认证状态");

        $i = 2;
        foreach($res as $key => $value){
            $PHPSheet->setCellValue('A'.$i,''.$value['Name']);
            $PHPSheet->setCellValue('B'.$i,''.$value['Number']);
            $PHPSheet->setCellValue('C'.$i,''.$value['DepartmentId']);
            $PHPSheet->setCellValue('D'.$i,''.$value['RoleName']);
            $PHPSheet->setCellValue('E'.$i,''.$value['Regist']);
            $i++;
        }
        $file_name = time().'.xls';
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename='.$file_name);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output");
    }
}
